<template>
  <div class="question-set-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <div>
            <h2>题目集管理</h2>
          <p>创建和管理不同职位的面试题目集</p>
          </div>
          <div><el-button type="primary" @click="showAddDialog">添加题目集</el-button></div>
        </div>
      </template>
      <!-- 筛选区域 -->
      <div class="filter-area">
        <el-form :model="filterForm" inline>
          <el-form-item label="职位">
            <el-select v-model="filterForm.position" placeholder="所有职位" style="width: 120px" clearable>
              <el-option
                v-for="item in positionOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="分类">
            <el-select v-model="filterForm.category" placeholder="所有分类" style="width: 120px" clearable>
              <el-option
                v-for="item in categoryOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="状态">
            <el-select v-model="filterForm.status" placeholder="所有状态" style="width: 120px" clearable>
              <el-option label="已启用" value="已启用" />
              <el-option label="已停用" value="已停用" />
            </el-select>
          </el-form-item>
         
          
          
          <el-form-item>
            <el-button type="primary" @click="handleFilter">应用筛选</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮区域 -->
       <div class="action">
        <div>
          <h3>题目集列表</h3>
        </div>
        <div class="action-area">
        <el-button type="primary" :icon="Refresh" @click="refreshData">刷新</el-button>
        <el-button type="success" :icon="Download" @click="exportData">导出</el-button>
      </div>
       </div>
      

      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="name" label="题目集名称" min-width="180" />
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="questionCount" label="题目数量" width="100" align="center" />
        <el-table-column prop="difficulty" label="难度" width="100" />
        <el-table-column prop="totalScore" label="总分值" width="100" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === '已启用' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="添加题目集" width="50%">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="题目集名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="应用职位">
          <el-select v-model="editForm.position" placeholder="请选择职位">
            <el-option
              v-for="item in positionOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="难度级别">
          <el-select v-model="editForm.difficulty" placeholder="请选择难度">
            <el-option label="初级" value="初级" />
            <el-option label="中级" value="中级" />
            <el-option label="高级" value="高级" />
            <el-option label="中高级" value="中高级" />
          </el-select>
        </el-form-item>
        <el-form-item label="总分值" prop="totalScore">
        <el-input-number v-model="editForm.totalScore" :min="1" :max="200" />
        <span class="score-hint">默认为100分</span>
      </el-form-item>
      <el-form-item label="题目集描述" prop="description">
        <el-input
          v-model="editForm.description"
          type="textarea"
          :rows="3"
          placeholder="请输入题目集描述"
        />
      </el-form-item>
      <el-form-item label="选择题目" prop="questions" required>
        <el-input
          v-model="searchQuery"
          placeholder="搜索题目..."
          clearable
          style="margin-bottom: 16px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <div class="question-list">
          <div
            v-for="question in filteredQuestions"
            :key="question.id"
            class="question-item"
            :class="{ selected: selectedQuestionIds.includes(question.id) }"
            @click="toggleQuestionSelection(question)"
          >
            <div class="question-title">{{ question.title }}</div>
            <div class="question-meta">
              <span>分类：{{ question.category }} | </span>
              <span>难度：{{ question.difficulty }} | </span>
              <span>分值：{{ question.score }}</span>
            </div>
          </div>
        </div>

        <div class="selection-summary">
          已选择 {{ selectedQuestionIds.length }} 题，总分值: {{ totalSelectedScore }}
        </div>
      </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.status">
            <el-radio label="已启用" />
            <el-radio label="已停用" />
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted,reactive,computed } from 'vue'
import { Edit, Delete, Download, Refresh } from '@element-plus/icons-vue'
import { getCategoryAdminList } from '@/api/ljl/questionSet.ts'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { QuestionSet,ICategoryParams} from '@/types/categoryAdmin'

// 筛选表单
const filterForm = ref({
  position: '',
  category: '',
  status: ''
})
// 查询参数
const listQuery = reactive<ICategoryParams>({
  page: 1,
  pageSize: 5,
  name: '',
  status: undefined
})


// 职位和分类选项
const positionOptions = ['前端工程师', '后端工程师', '全栈工程师', 'UI设计师', '产品经理']

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 编辑对话框
const dialogVisible = ref(false)
const editForm = ref<Partial<QuestionSet>>({})

// 获取数据
const fetchData = async() => {
  const res:any = await getCategoryAdminList()
  console.log('2222',res);
  tableData.value = res.list
  total.value = res.list.length
}

// 筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchData()
}
// 搜索查询
const searchQuery = ref('')
// 已选择的题目ID
const selectedQuestionIds = ref<number[]>([])
// 过滤后的题目列表
interface Question {
  id: number
  title: string
  category: string
  difficulty: string
  score: number
}
// 题目列表数据
const questions = ref<Question[]>([
  {
    id: 1,
    title: 'JavaScript闭包原理和应用',
    category: '技术能力',
    difficulty: '中级',
    score: 10
  },
  {
    id: 2,
    title: 'React组件生命周期',
    category: '技术能力',
    difficulty: '中级',
    score: 8
  },
  {
    id: 3,
    title: 'HTTP缓存机制详解',
    category: '技术能力',
    difficulty: '高级',
    score: 12
  },
  {
    id: 4,
    title: '大型前端项目架构设计',
    category: '系统设计',
    difficulty: '高级',
    score: 15
  }
])

const filteredQuestions = computed(() => {
  if (!searchQuery.value) return questions.value
  return questions.value.filter(question =>
    question.title.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 计算已选题目总分
const totalSelectedScore = computed(() => {
  return selectedQuestionIds.value.reduce((total, id) => {
    const question = questions.value.find(q => q.id === id)
    return total + (question?.score || 0)
  }, 0)
})

// 切换题目选择状态
const toggleQuestionSelection = (question: Question) => {
  const index = selectedQuestionIds.value.indexOf(question.id)
  if (index === -1) {
    selectedQuestionIds.value.push(question.id)
  } else {
    selectedQuestionIds.value.splice(index, 1)
  }
}


// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    position: '',
    category: '',
    status: ''
  }
  handleFilter()
}

// 刷新数据
const refreshData = () => {
  fetchData()
}

// 导出数据
const exportData = () => {
  ElMessage.success('导出功能待实现')
}

// 编辑
const handleEdit = (row: QuestionSet) => {
  editForm.value = { ...row }
  Object.assign(filterForm, {
    name: row.name,
    category: row.category,
    status: row.status
  })
  dialogVisible.value = true
}
const showAddDialog = (row: QuestionSet) =>{
  editForm.value = { ...row }
  dialogVisible.value = true
}
// 确认编辑
const confirmEdit = () => {
  ElMessage.success('编辑成功')
  dialogVisible.value = false
  fetchData()
}

// 删除
const handleDelete = (row: QuestionSet) => {
  ElMessageBox.confirm(`确定要删除题目集 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 初始化加载数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.question-set-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
}

.card-header p {
  margin: 5px 0 0;
  color: #888;
  font-size: 14px;
}

.filter-area {
  margin-bottom: 20px;
}

.action{
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.action-area {
  
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
.question-list {
  width: 100%;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.question-item {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.question-item:hover {
  background-color: #f5f7fa;
}

.question-item.selected {
  background-color: #ecf5ff;
  border-left: 3px solid #409eff;
}

.question-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.question-meta {
  font-size: 12px;
  color: #909399;
}

.selection-summary {
  margin-top: 12px;
  font-size: 14px;
  color: #606266;
}

.score-hint {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  align-items: center;
}
</style>